package com.lrkj.property.service.impl;

import com.lrkj.common.annotation.DataScope;
import com.lrkj.common.constant.OrgConstants;
import com.lrkj.common.constant.PropertyConstants;
import com.lrkj.common.core.domain.entity.OrgTree;
import com.lrkj.common.exception.BaseException;
import com.lrkj.common.utils.DateUtils;
import com.lrkj.common.utils.SecurityUtils;
import com.lrkj.common.utils.StringUtils;
import com.lrkj.common.utils.uuid.IdUtils;
import com.lrkj.framework.utils.NumberUtils;
import com.lrkj.property.domain.Community;
import com.lrkj.property.domain.Floor;
import com.lrkj.property.domain.Room;
import com.lrkj.property.domain.Unit;
import com.lrkj.property.mapper.FloorMapper;
import com.lrkj.property.service.ICommunityService;
import com.lrkj.property.service.IFloorService;
import com.lrkj.property.service.IRoomService;
import com.lrkj.property.service.IUnitService;
import com.lrkj.property.vo.FloorVo;
import com.lrkj.system.service.IOrgTreeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 楼栋信息Service业务层处理
 *
 * @author yajun_ren
 * @date 2021-07-22
 */
@Service
public class FloorServiceImpl implements IFloorService {
    @Autowired
    private FloorMapper floorMapper;


    @Autowired
    private ICommunityService communityService;


    @Autowired
    private IUnitService unitService;

    @Autowired
    private IRoomService roomService;

    @Autowired
    private IOrgTreeService orgTreeService;


    /**
     * 查询楼栋信息
     *
     * @param id 楼栋信息ID
     * @return 楼栋信息
     */
    @Override
    public Floor selectFloorById(String id) {
        return floorMapper.selectFloorById(id);
    }

    /**
     * 查询楼栋信息列表
     *
     * @param floor 楼栋信息
     * @return 楼栋信息
     */
    @Override
    @DataScope(deptAlias = "t")
    public List<Floor> selectFloorList(Floor floor) {
        return floorMapper.selectFloorList(floor);
    }

    /**
     * 新增楼栋信息
     *
     * @param floor 楼栋信息
     * @return 结果
     */
    @Override
    public int insertFloor(Floor floor) {
        floor.setId(IdUtils.simpleUUID());
        floor.setCreateBy(SecurityUtils.getUsername());
        floor.setCreateTime(DateUtils.getNowDate());
        this.setUnitInfo(floor);
        return floorMapper.insertFloor(floor);
    }

    /**
     * 修改楼栋信息
     *
     * @param floor 楼栋信息
     * @return 结果
     */
    @Override
    public int updateFloor(Floor floor) {
        this.setUnitInfo(floor);
        floor.setUpdateBy(SecurityUtils.getUsername());
        floor.setUpdateTime(DateUtils.getNowDate());
        return floorMapper.updateFloor(floor);
    }

    private void setUnitInfo(Floor bean) {
        Community parentBean = communityService.selectCommunityById(bean.getCommunityId());
        bean.setAncestors(parentBean.getAncestors() + "," + bean.getCommunityId());
        bean.setDeptId(parentBean.getDeptId());
        orgTreeService.insertOrgTree(bean.getId(), bean.getFloorName(), bean.getCommunityId(), OrgConstants.floor, bean.getAncestors(), bean.getFloorNum());
    }

    /**
     * 批量删除楼栋信息
     *
     * @param ids 需要删除的楼栋信息ID
     * @return 结果
     */
    @Override
    public int deleteFloorByIds(String[] ids) {
        for (String floorId : ids) {
            this.deleteVerify(floorId);
        }
        orgTreeService.deleteOrgTreeByIds(ids);
        return floorMapper.deleteFloorByIds(ids);
    }

    /**
     * 删除楼栋信息信息
     *
     * @param id 楼栋信息ID
     * @return 结果
     */
    @Override
    public int deleteFloorById(String id) {
        this.deleteVerify(id);
        orgTreeService.deleteOrgTreeById(id);
        return floorMapper.deleteFloorById(id);
    }

    @Override
    @Transactional
    public int generationUnitAndLayer(Floor floor) {
        Floor bean = floorMapper.selectFloorById(floor.getId());
        List<Unit> units = unitService.selectUnitList(Unit.createFloorId(bean.getId()));
        if (null != units && units.size() > 0) {
            throw new BaseException("一键生成单元失败【已经存在单元信息】");
        }
        Community community = communityService.selectCommunityById(bean.getCommunityId());

        List<Unit> savaUnits = new ArrayList<>();
        if (null != bean) {
            for (int i = 0; i < Integer.valueOf(bean.getUnitNum()); i++) {
                String num = (i + 1) + "";
                Unit unit = new Unit();
                unit.setId(IdUtils.simpleUUID());
                unit.setFloorId(bean.getId());
                unit.setUnitNum(num);
                unit.setUnitName(num + "单元");
                unit.setLayerNum(bean.getLayerNum());
                unit.setDeptId(community.getDeptId());
                unit.setCommunityId(bean.getCommunityId());
                unit.setCreateBy(SecurityUtils.getUsername());
                unit.setCreateTime(DateUtils.getNowDate());
                unit.setAncestors(bean.getAncestors() + "," + unit.getId());
                savaUnits.add(unit);
            }
            unitService.doSaveList(savaUnits);
            savaUnits.stream().forEach(x -> {
                OrgTree orgTree = new OrgTree();
                orgTree.setId(x.getId());
                orgTree.setName(x.getUnitName());
                orgTree.setParentId(x.getFloorId());
                orgTree.setModelType(OrgConstants.unit);
                orgTree.setAncestors(x.getAncestors());
                orgTree.setOrderNum(Integer.valueOf(x.getUnitNum()));
                orgTreeService.insertOrgTree(orgTree);
            });
        }
        return 1;
    }

    @Override
    public int selectCount(Floor floor) {
        return floorMapper.selectCount(floor);
    }

    @Override
    @Transactional
    public int addFloorNum(FloorVo floor) {
        this.checkParams(floor);
        Community community = communityService.selectCommunityById(floor.getCommunityId());
        List<Floor> savaFloors = new ArrayList<>();
        //1、获取当前小区楼最大编号
        int maxFloorNum = floorMapper.maxFloorNum(floor.getCommunityId());
        //2、创建楼栋信息
        for (Integer i = 0; i < floor.getFloorNum(); i++) {
            maxFloorNum++;
            //创建楼栋信息
            Floor newFloor = this.floorFactory(floor, maxFloorNum, community);
            savaFloors.add(newFloor);
            //通过楼栋表回去当前小区最大楼栋编号,然后加 1
        }
        return floorMapper.batchAddData(savaFloors);
    }

    //楼栋工厂
    private Floor floorFactory(FloorVo floor, int floorNum, Community community) {
        AtomicInteger roomNum = new AtomicInteger(1);
        Floor bean = new Floor();
        bean.setId(IdUtils.simpleUUID());
        bean.setCommunityId(community.getId());
        bean.setFloorName("第" + floorNum + "楼栋");
        bean.setFloorNum(floorNum + "");
        bean.setUnitNum(floor.getUnitNum());
        bean.setLayerNum(floor.getLayerNum());
        bean.setRoomNum(floor.getRoomNum());
        bean.setCreateBy(SecurityUtils.getUsername());
        bean.setCreateTime(DateUtils.getNowDate());
        bean.setAncestors(community.getAncestors() + "," + bean.getCommunityId());
        bean.setDeptId(community.getDeptId());
        bean.setDataSourceId("系统创建");
        bean.setRoomRule(floor.getRoomRule());
        orgTreeService.insertOrgTree(bean.getId(), bean.getFloorName(), bean.getCommunityId(), OrgConstants.floor, bean.getAncestors(), floorNum);
        //单元工厂
        this.unitFactory(floor, bean, community, roomNum);
        return bean;
    }

    //单元工厂
    private void unitFactory(FloorVo floorVo, Floor floor, Community community, AtomicInteger floorRoomNum) {
        List<Unit> savaUnits = new ArrayList<>();
        for (Integer i = 0; i < floor.getUnitNum(); i++) {
            int unitNum = (i + 1);
            Unit bean = new Unit();
            bean.setId(IdUtils.simpleUUID());
            bean.setFloorId(floor.getId());
            bean.setUnitNum(unitNum+"");
            bean.setUnitName("第" + unitNum + "单元");
            bean.setLayerNum(floor.getLayerNum());
            bean.setRoomNum(floor.getRoomNum());
            bean.setDeptId(community.getDeptId());
            bean.setCommunityId(community.getId());
            bean.setCreateBy(SecurityUtils.getUsername());
            bean.setCreateTime(DateUtils.getNowDate());
            bean.setAncestors(floor.getAncestors() + "," + floor.getId());
            bean.setDataSourceId("系统创建");
            orgTreeService.insertOrgTree(bean.getId(), bean.getUnitName(), bean.getFloorId(), OrgConstants.unit, bean.getAncestors(), unitNum);
            this.roomFactory(floorVo, floor, bean, community, floorRoomNum);
            savaUnits.add(bean);

        }
        unitService.doSaveList(savaUnits);
    }

    //房屋工厂
    private void roomFactory(FloorVo floorVo, Floor floor, Unit unit, Community community, AtomicInteger floorRoomNum) {
        List<Room> savaRooms = new ArrayList<>();
        for (Integer i = 0; i < unit.getLayerNum(); i++) {
            Integer layerNum = i + 1;//层数

            for (int j = 0; j < unit.getRoomNum(); j++) {
                Room bean = new Room();
                bean.setId(IdUtils.simpleUUID());
                bean.setUnitId(unit.getId());
                bean.setFloorId(unit.getFloorId());
                bean.setCommunityId(community.getId());
                bean.setDeptId(community.getDeptId());

                Integer roomNum = j + 1;//房间数
                String houseNum = "";
                //门牌号生成规则
                if (StringUtils.isNotEmpty(floorVo.getRoomRule())) {
                    if (floorVo.getRoomRule().equals(PropertyConstants.room_rule_10)) {
                        //按照楼统一编排
                        houseNum = NumberUtils.frontCompWithZore(floorRoomNum.get(), 3);
                        bean.setRoomOrder(floorRoomNum.get());
                        floorRoomNum.incrementAndGet();
                    } else if (floorVo.getRoomRule().equals(PropertyConstants.room_rule_20)) {
                        //按照楼层和房间号编排
                        houseNum = NumberUtils.frontCompWithZore(layerNum, 2) + NumberUtils.frontCompWithZore(roomNum, 2);
                        bean.setRoomOrder(roomNum);
                    }
                }

                bean.setLayerNum(layerNum + "");
                bean.setRoomNum(houseNum);
                bean.setDataSourceId("系统创建");
                bean.setStatusCd(PropertyConstants.housing_status_10001);
                bean.setCreateTime(DateUtils.getNowDate());
                bean.setCreateBy(SecurityUtils.getUsername());
                bean.setRoomName(floor.getFloorNum() + "-" + unit.getUnitNum() + "-" + houseNum);
                bean.setAncestors(unit.getAncestors() + "," + unit.getId());
                bean.setState("10001");
                String cityName = "";
                if(StringUtils.isNotEmpty(community.getCityName())){
                    String[] split = community.getCityName().split("/");
                    for(String s:split){
                        cityName+=s;
                    }
                }
                bean.setAddress(cityName+community.getCommunityName()+floor.getFloorName()+unit.getUnitName()+bean.getRoomNum());
                orgTreeService.insertOrgTree(bean.getId(), bean.getRoomNum(), bean.getUnitId(), OrgConstants.room, bean.getAncestors(),Integer.valueOf( bean.getRoomNum()));
                savaRooms.add(bean);
            }
        }
        roomService.doSaveList(savaRooms);

    }


    private void checkParams(FloorVo floor) {
        if (floor.getFloorNum() < 1) {
            throw new BaseException("楼栋数量必须大于0");
        }
        if (floor.getUnitNum() < 1) {
            throw new BaseException("单元数量必须大于0");
        }
        if (floor.getLayerNum() < 1) {
            throw new BaseException("单元层数必须大于0");
        }
        if (floor.getRoomNum() < 1) {
            throw new BaseException("单元户数必须大于0");
        }
    }


    /***
     * 删除楼栋信息,校验关联信息
     *
     * **/
    private void deleteVerify(String floorId) {
        Unit eg = new Unit();
        eg.setFloorId(floorId);
        int count = unitService.selectCount(eg);
        if (count > 0) {
            throw new BaseException("删除楼栋失败,请先删除关联的单元信息!");
        }
    }

    /**
     * 批量新增楼栋信息信息
     *
     * @param floors 楼栋信息对象
     */
    public int batchAddData(List<Floor> floors) {
        return floorMapper.batchAddData(floors);
    }
}
